package com.doudou.commons.config;

import com.doudou.commons.serializer.JsonRedisSerializer;
import com.doudou.commons.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: 傻男人
 * @Date: 2020/6/10 13:22
 * @Version: 1.0
 * @Description:
 */
@Slf4j
@ConditionalOnClass(RedisTemplate.class)
@Configuration
public class RedisAutoConfiguration {

    @Bean
    @Primary
    public RedisUtil redisUtil() {
        RedisTemplate redisTemplate = new RedisTemplate();
        return new RedisUtil(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(new JsonRedisSerializer<>(Object.class));
        //value hashmap序列化
        template.setHashValueSerializer(redisSerializer);
        //key haspmap序列化
        template.setHashKeySerializer(redisSerializer);

        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisTemplate checkRedisConnection(RedisConnectionFactory factory){
        RedisTemplate redisTemplate = redisTemplate(factory);
        RedisConnectionFactory redisConnectionFactory = redisTemplate.getConnectionFactory();
        try{
            RedisConnection redisConnection = redisConnectionFactory.getConnection();
            redisConnection.isClosed();
        }catch (Exception e){
            log.error("Unable to connect redis");
        }
        return redisTemplate;
    }
}
